package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyCatalog;
import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyCatalogMapper;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyCatalogService;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //设置最大序列
        if (strategyDetail.getSequence()==null){
            int max=strategyDetailMapper.selectMaxSequence(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(++max);
        }

        //设置发布时间
        if(strategyDetail.getState()==StrategyDetail.STATE_RELEASE){
            strategyDetail.setReleaseTime(new Date());
        }

        //获取内容对象
        StrategyContent strategyContent = strategyDetail.getContent();

        if(strategyDetail.getId()==null){
            //设置创建时间
            strategyDetail.setCreateTime(new Date());
            //新增文章
            strategyDetailMapper.insert(strategyDetail);
            //获取自动增长的id
            strategyContent.setId(strategyDetail.getId());
            //新增内容
            strategyContentMapper.insert(strategyContent);

        }else{
            //更新文章
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            //获取id
            strategyContent.setId(strategyDetail.getId());
            //更新文章内容
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        }
    }

    @Override
    public StrategyDetail selectByDetailId(Long id) {
        StrategyDetail detail = strategyDetailMapper.selectByPrimaryKey(id);
        StrategyContent content = strategyContentMapper.selectByPrimaryKey(id);
        detail.setContent(content);
        return detail;

    }

    @Override
    public StrategyContent getStrategyContent(Long detailId) {
        return strategyContentMapper.selectByPrimaryKey(detailId);
    }
}
